import { t } from 'i18next'
import React, { useEffect, useMemo, useState } from 'react'
import { DatePicker } from '@kedacom/react-next'
import type { Dayjs } from 'dayjs'
export interface CalendarDatePickerProps {
	selectedDate: Dayjs
	setSelectedDate: (val: Dayjs) => void
}

const weekList = [t('一'), t('二'), t('三'), t('四'), t('五'), t('六'), t('日')]

export default function CalendarDatePicker(props: CalendarDatePickerProps) {
	const { selectedDate, setSelectedDate } = props
	const [innerSelectedDate, setInnerSelectDate] = useState(selectedDate)
	const dateList = useMemo(() => {
		let monthFirstDay = innerSelectedDate.startOf('month')
		let monthStartDay = monthFirstDay.startOf('week')
		return new Array(42).fill('').map((_, index) => monthStartDay.add(index, 'day'))
	}, [innerSelectedDate])
	useEffect(() => {
		setInnerSelectDate(selectedDate)
	}, [selectedDate])
	const handleSelect = (day: Dayjs) => {
		setInnerSelectDate(day)
		setSelectedDate(day)
	}
	return (
		<>
			<DatePicker
				picker="month"
				value={innerSelectedDate}
				onChange={(e, str, val) => handleSelect(val)}
				inputReadOnly
				i18n={{
					confirm: t('确认'),
					year: t('年'),
					month: [
						t('1月'),
						t('2月'),
						t('3月'),
						t('4月'),
						t('5月'),
						t('6月'),
						t('7月'),
						t('8月'),
						t('9月'),
						t('10月'),
						t('11月'),
						t('12月'),
					],
					week: [t('日'), t('一'), t('二'), t('三'), t('四'), t('五'), t('六')],
				}}
			/>
			<div className="date-panel">
				<div className="panel-title">
					{weekList.map((week, index) => (
						<div className="date-title" key={index}>
							{week}
						</div>
					))}
				</div>
				<div className="panel-date">
					{dateList.map((date, index) => {
						let isOtherMonth = !date.isSame(innerSelectedDate, 'month')
						let isCurDay = date.isSame(innerSelectedDate, 'day')
						let isCurWeek =
							date.isSameOrAfter(innerSelectedDate.startOf('week')) &&
							date.isSameOrBefore(innerSelectedDate.endOf('week'))
						return (
							<div
								key={index}
								className={`date-item
                                ${isOtherMonth ? 'isOtherMonth' : ''}
                                ${isCurDay ? 'isCurDay' : ''}
                                ${isCurWeek ? 'isCurWeek' : ''}`}
								onClick={() => handleSelect(date)}
							>
								{date.format('DD')}
							</div>
						)
					})}
				</div>
			</div>
		</>
	)
}
